package com.zy.service.bs.impl;

import com.zy.entity.enums.bs.ShelvesEnum;
import com.zy.pojo.exceptions.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zy.dao.bs.GoodsDao;
import com.zy.entity.enums.StatusEnum;
import com.zy.entity.bs.Goods;
import com.zy.pojo.query.bs.GoodsQuery;
import com.zy.pojo.vos.common.PageVo;
import com.zy.service.base.impl.BaseServiceImpl;
import com.zy.service.bs.GoodsService;
import com.zy.utils.DateUtil;

import java.util.Objects;

@Service("goodsService")
public class GoodsServiceImpl extends BaseServiceImpl<Goods> implements GoodsService {

	@Autowired
	private GoodsDao goodsDao;

	@Override
	public PageVo pageGoods(GoodsQuery goodsQuery, Integer start, Integer limit) {
		return new PageVo(start, limit, this.goodsDao.countGoods(goodsQuery), this.goodsDao.listGoods(goodsQuery, start, limit));
	}

	@Override
	public void saveGoods(Goods goods) {
		long time = DateUtil.getTime();
		goods.setIsShelves(ShelvesEnum.NO.getValue());
		goods.setCreateTime(time);
		goods.setModifyTime(time);
		goods.setStatus(StatusEnum.NORMAL.getValue());
		this.goodsDao.save(goods);
	}
	
	@Override
	public void updateGoods(Goods goods) {
		goods.setModifyTime(DateUtil.getTime());
		this.goodsDao.updateByPrimaryKeySelective(goods);
	}

	@Override
	public void removeGoods(long id) {
		try {
			this.goodsDao.removeByPrimaryKey(id);
		} catch (Exception e) {
			log.info(e.getMessage(),e);
			Goods goods = new Goods();
			goods.setId(id);
			goods.setModifyTime(DateUtil.getTime());
			goods.setStatus(StatusEnum.DELETE.getValue());
			this.goodsDao.updateByPrimaryKeySelective(goods);
		}
	}

	@Override
	public void recover(long id) {
		Goods goods = new Goods();
		goods.setId(id);
		goods.setModifyTime(DateUtil.getTime());
		goods.setStatus(StatusEnum.NORMAL.getValue());
		this.goodsDao.updateByPrimaryKeySelective(goods);
	}

	@Override
	public void shelf(Goods goods) {
		Goods newGoods = goodsDao.getByPrimaryKey(goods.getId());
		if(Objects.equals(newGoods.getIsShelves(),ShelvesEnum.YES.getValue())){
			throw new ServiceException("该商品已上架");
		}
		goods.setIsShelves(ShelvesEnum.YES.getValue());
		goodsDao.updateByPrimaryKeySelective(goods);
	}

	@Override
	public void cancel(Goods goods) {
		Goods newGoods = goodsDao.getByPrimaryKey(goods.getId());
		if(Objects.equals(newGoods.getIsShelves(),ShelvesEnum.NO.getValue())){
			throw new ServiceException("该商品已下架");
		}
		goods.setIsShelves(ShelvesEnum.NO.getValue());
		goodsDao.updateByPrimaryKeySelective(goods);
	}

}
